﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mbr.Reviews.Core.Contracts;
using Mbr.Reviews.Core.Exceptions;
using Mbr.Reviews.Core.ProductProviders;
using Mbr.Reviews.Core.DtoMappers;

namespace Mbr.Reviews.Core
{
    public class ProductFinder
    {
        private readonly ICrawlForProducts productCrawler;

        public ProductFinder(ICrawlForProducts productCrawler)
        {
            this.productCrawler = productCrawler;
        }
        public ProductFinder() : this(null) { }

        public IEnumerable<Product> Find(params string[] keywords)
        {
            if (keywords == null || keywords.All(w => string.IsNullOrWhiteSpace(w)))
            {
                throw new NoKeywordsException("keywords", "All of the provided keywords were null, empty or white spaces");
            }

            var results = new InMemoryProductProvider().Find(keywords).ToDomain();

            if (!results.Any())
            {
                BeginCrawling();
            }

            return results;
        }

        private void BeginCrawling()
        {
            if (productCrawler != null)
            {
                productCrawler.BeginCrawl();
            }
        }
    }
}
